package com.baosight.risk.common.aspects;

import com.baosight.iplat4j.core.web.threadlocal.UserSession;
import com.baosight.risk.api.xtzy.IXtzyIntegralService;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.IntegralType;
import com.baosight.risk.common.utils.JSONUtils;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.enums.BusinessStatus;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.ServletUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.service.xtzy.entity.XtzyIntegral;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author duanyongqiang
 * @date 2019.3.22
 */
@Slf4j
@Aspect
public class LogAspect {

    @Autowired
    private IXtzyIntegralService integralService;

    /**
     * 配置切点
     */
    @Pointcut("@annotation(com.baosight.risk.common.annotation.Log)")
    public void logPointCut() {

    }

    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Exception {
        handleLog(joinPoint);
        handleIntegral(joinPoint);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) throws Exception {
        log.info(e.getMessage());
        handleLog(joinPoint);
    }

    /**
     * @description 日志处理
     */
    protected void handleLog(final JoinPoint joinPoint) throws Exception {

        // 获得注解
        Log controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }
        //保存数据库
        SysOperLog operLog = (SysOperLog) BeanUtils.initBean(new SysOperLog());
        operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
        // 请求的地址
        operLog.setOperIp(UserSession.getIpaddress());
        operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        operLog.setMethod(className + "." + methodName + "()");
        // 处理设置注解上的参数
        getControllerMethodDescription(controllerLog, operLog);
        // 保存数据库
        AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
    }

    /**
     * @description 积分处理
     * @author CuiShiHao
     */
    protected void handleIntegral(final JoinPoint joinPoint) throws Exception {
        // 获得注解
        Log controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }

        // 获得积分处理标签
        IntegralType Type = controllerLog.integralType();
        if (Type.toValue() == 0) {
            return;
        }
        integralService.insertIntegral(null, Type);
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log 切点
     * @return 方法描述
     * @throws Exception
     * @Param operLog
     */
    public void getControllerMethodDescription(Log log, SysOperLog operLog) throws Exception {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(operLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(SysOperLog operLog) throws Exception {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        String params = JSONUtils.marshal(map);
        operLog.setOperParam(StringUtils.substring(params, 0, 255));
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

}
